package com.zzyq.pc.common.plugin.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import com.zzyq.pc.common.StandardDataFormat;
import com.zzyq.pc.common.base.CodeMsg;
import com.zzyq.pc.utils.HttpUtils;

/**
 * 
 * <p>
 * 
 * @Title: RoleFilter.java
 * @Description: 角色校验过滤器
 * @author: Sywd丶吴迪
 * @date: 2017年8月30日 上午10:12:53
 * @version V1.0
 *          <p>
 */
public class RoleFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception {
        try {
            if (null == mappedValue) {
                return false;
            }
            String[] roles = (String[]) mappedValue;
            Subject subject = getSubject(request, response);
            for (String role : roles) {
                if (subject.hasRole(role)) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        if (subject.getPrincipal() == null) {
            saveRequest(request);
            if (HttpUtils.isAjax(request)) {// AJAX请求
                String str = HttpUtils.formatData(new StandardDataFormat(), CodeMsg.CODE_LOGIN_REQUEST,
                        CodeMsg.MSG_LOGIN_REQUEST, null);
                HttpUtils.out(response, str);
            } else {
                WebUtils.issueRedirect(request, response, HttpUtils.LOGIN_URL);
                // request.getRequestDispatcher(HttpUtils.LOGIN_URL).forward(request,
                // response);
            }
        } else {
            String str = HttpUtils.formatData(new StandardDataFormat(), CodeMsg.CODE_POWER_ERROR,
                    CodeMsg.MSG_POWER_ERROR, null);
            HttpUtils.out(response, str);
        }
        return false;
    }

}
